package myky.com.doctorapp.utils;


import android.content.Context;
import android.content.res.AssetManager;
import android.net.http.SslError;
import android.os.Build;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * Created by 61904 on 2017/3/22.
 */

public class HtmlUtils {

    private static Set<String> offlineResources = new HashSet<>();
    private static Set<String> offlineResources2 = new HashSet<>();
    private static WebView webView;
    private static JavasInterface javasInterface;
    private static Context context;
    private static Html_java_call_js html_java_call_js;
    private static Html_js_call_java html_js_call_java;
    private static Html_photo_to_js html_photo_to_js;
    private static Html_back_to_js html_back_to_js;


    public static void setjsInterface(Context contexts,WebView web, String data){

        webView=web;
        context=contexts;
        //支持js
        javasInterface = new JavasInterface(webView);
        webView.setWebChromeClient(new WebChromeClient());
        setSettings(web.getSettings());
//      web.loadUrl("file:///android_asset/h5-assert/kxz.html");
        fetchOfflineResources();
        setWebResource();
        webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    }



    /**
     * 设置JS和JAVA交互并添加调方法的接口
     */
    private static void setSettings(WebSettings settings) {


        webView.addJavascriptInterface(javasInterface, "jsInterface");
        //设置编码格式
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);

    }





    //加载本地cs,js文件
    private static void setWebResource() {

        webView.setWebViewClient(new WebViewClient(){


            @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        Log.d("WebViewActivity", "shouldInterceptRequest thread id: " + Thread.currentThread().getId());
        int lastSlash = url.lastIndexOf("/");
        if(lastSlash != -1) {
            String suffix = url.substring(lastSlash + 1);
            String path=null;
            if(offlineResources.contains(suffix)) {

                path="h5-assert/";
            }else if (offlineResources2.contains(suffix)){
                path= "app_reservation/";
            }
                String mimeType;
                if(suffix.endsWith(".js")) {
                    mimeType = "application/x-javascript";
                } else if(suffix.endsWith(".css")) {
                    mimeType = "text/css";


                } else if(suffix.endsWith(".woff?v=3.2.1")){

                    Log.i("out","woff"+offlineResources);
                    mimeType = "application/x-font-woff";
                }else {
                    mimeType = "text/html";
                }


                try {
                    InputStream is = context.getAssets().open(path + suffix);
                    Log.i("shouldInterceptRequest", "use offline resource for: " + url);
                    WebResourceResponse response=new WebResourceResponse(mimeType, "UTF-8", is);
                    Map<String, String> header=new HashMap();
                        header.put("Access-Control-Allow-Origin","*");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        response.setResponseHeaders(header);
                    }
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
        Log.i("shouldInterceptRequest", "load resource from internet, url: " + url);
        return super.shouldInterceptRequest(view, url);



    }


            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });


    }
    //先取出本地文件的路径
    private static void fetchOfflineResources() {
        AssetManager am = context.getAssets();
        try {
            String[] res = am.list("h5-assert");
            String[] res2 = am.list("app_reservation");
            if(res != null) {
                Collections.addAll(offlineResources, res);
                Collections.addAll(offlineResources2, res2);
                Log.i("out","app_reservation."+offlineResources2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class JavasInterface {
        private WebView mWebView;


        // 构造方法，传入一个参数WebView
        public JavasInterface(WebView webView) {
            this.mWebView = webView;
        }

        // 这个方法是js调用java
        @JavascriptInterface
        public void js_call_java(String payload) {

            html_js_call_java.js_call_java(payload);

        }
        // 这个方法是js调用java
        @JavascriptInterface
        public void sendJson(String payload) {

            html_js_call_java.js_call_java(payload);

        }

        /**
         * java端提供JS调用相册相机获取图片的方法
         */
        @JavascriptInterface
        public String photo_to_js(String imageid) {


            return html_photo_to_js.photo_to_js(imageid);
        }

        public void java_call_js(){


            html_java_call_js.java_call_js();
        }
        @JavascriptInterface
        public void back_to_js(){


            html_back_to_js.back_to_js();
        }

    }

    /**
     * 设置H5交互的方法     *
     *
     *
     */
    public static void js_java(Html_js_call_java html_js_call_javas){

            html_js_call_java=html_js_call_javas;
        }

    public static void java_js(Html_java_call_js html_java_call_jss){

        html_java_call_js=html_java_call_jss;
    }
    public static void photo_js(Html_photo_to_js html_photo_to_jss){

       html_photo_to_js=html_photo_to_jss;
    }

    public static void back_js(Html_back_to_js html_back_to_jss){

        html_back_to_js=html_back_to_jss;
    }
    /**
     * 设置H5交互的的接口
     */


    public interface Html_js_call_java {
        void js_call_java(String data);
    }


    public interface Html_java_call_js {
         void java_call_js();
    }


    public interface Html_photo_to_js {

         String photo_to_js(String imageid);
    }

    public interface Html_back_to_js {

        void back_to_js();
    }

}
